<?php

// -----------------------------------------------------------------------------

if (!isset($_GET['date'])) {
    exit("需要指定有效的日期。");
}

$date = htmlspecialchars($_GET['date']);

if ($date == "undefinedundefined") {
    exit("无效的日期。");
}

// -----------------------------------------------------------------------------

include "global.php";
include "auth.php";

// -----------------------------------------------------------------------------

function getDateDetailInfor(string $date) {
    if (is_string($date)) {
        $dt = new DateTime($date);
        $arr = [];
        $arr["dayOfWeek"] = $dt->format("w");
        $arr['dayOfMonth'] = $dt->format("d");
        $arr['monthAndDay'] = $dt->format("md");
        return $arr;
    }
}

function getAllContentOfSpecificDate(string $date, $db) {

    $arr = getDateDetailInfor($date);

    $data = [];
    $data["daily"] = $db->readFromDaily();
    $data["weekly"] = $db->readFromWeekly($arr["dayOfWeek"]);
    $data["monthly"] = $db->readFromMonthly($arr["dayOfMonth"]);
    $data["yearly"] = $db->readFromYearly($arr["monthAndDay"]);
    $data["specificDate"] = $db->readFromSpecificDate($date);

    return $data;

}

function PHPEOLToBr(string $content) {
    $str = str_replace(PHP_EOL, "<br />", $content);
    $arr = explode("<br />", $str);
    $result = "";
    foreach ($arr as $item) {
        if (empty($item) || $item == "\r") {
            $result .= "<br />";
        } elseif ($item[0] == "#" || $item == "暂无。") {
            $result .= $item;
            $result .= "<br />";
        } else {
            $result .= <<<BBB
            <input class="taskItem" type="checkbox" />
            <span class="taskTitle" role="button">$item</span>
            <br />
        BBB;
        }
    }
    return $result;
}

// -----------------------------------------------------------------------------

// 设置时区
date_default_timezone_set($region);

// 前一天
$dt = new DateTime($date);

// input date 输入的日期形如 2022-10-23，不同于 20221023
// 注：现在前端代码已经修改过了，input date 输入的日期不再包含「-」了，但是这行代码继续保留，稳妥起见……
$dateStr = $dt->format("Ymd");

$yesterday = $dt->sub(new DateInterval("P1D"));
$yesterdayStr = $yesterday->format("Ymd");

// 后一天
$tomorrow = $yesterday->add(new DateInterval("P2D"));
$tomorrowStr = $tomorrow->format("Ymd");

// 今天
$today = new DateTime("today");
$todayStr = $today->format("Ymd");

$contents = getAllContentOfSpecificDate($dateStr, $db);

// -----------------------------------------------------------------------------
?>
<html>
<head>
    <meta charset="utf-8">
    <title>Todo - <?php echo $date; ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="resources/bootstrap-5.2.0-beta1-dist/css/bootstrap.min.css">
    <style>
        a {
            text-decoration: none;
        }
        .big {
            font-size: large;
        }
    </style>
    <base target="_blank" />
</head>
<body>

<!-- ----------------------------------------------------------------------- -->
<?php include "globalNavbar.php"; ?>
<!-- ----------------------------------------------------------------------- -->

<div class="container container-fluid mt-3 mb-3">

    <div class="card">
        <div class="card-header d-flex">

            <div class="w-100">

		<?php

			$days = ["日", "一", "二", "三", "四", "五", "六"];
			$dateDetailInfor = getDateDetailInfor($dateStr);
			$index = $dateDetailInfor['dayOfWeek'];
			$xingqi = "周" . $days[$index];
			echo <<<BBB
				$date $xingqi
			BBB;

		?>

                <a href="viewByDate.php?date=<?php echo $yesterdayStr; ?>" class="badge text-bg-primary" target="_self">前一天</a>
                <a href="viewByDate.php?date=<?php echo $tomorrowStr; ?>" class="badge text-bg-primary" target="_self">后一天</a>
                <a href="viewByDate.php?date=<?php echo $todayStr; ?>" class="badge text-bg-primary" target="_self">今天</a>
            </div>


<?php
$hiden = <<<BBB
<div class="flex-shrink-0 mt-1">
	<a href="#" id="btnResetFinishedTask" class="badge text-bg-info" target="_self">重置状态</a>
</div>

BBB;
?>

        </div>

    </div>

    <?php

    $dateDetailInfor = getDateDetailInfor($dateStr);

    $content = $contents['specificDate'];
    if (empty($content)) {
        $content = "暂无。";
    }
    $content = PHPEOLToBr($content);
    echo <<<BBB
        <div class="card mt-2">
        
            <div class="card-header d-flex bg-info">
                <div class="w-100 big">
                    当日
                </div>
                <div class="flex-shrink-0" id="btnEditToday">
                    <a href="edit.php?from=specificDate&date=$dateStr" class="badge text-bg-danger">编辑</a>
                </div>
            </div> 
            
            <div class="card-body">
                $content
            </div>
        </div>
    BBB;

    if (!empty($contents['daily'])) {
        $content = $contents['daily'];
        $content = PHPEOLToBr($content);
        echo <<<BBB
            <div class="card mt-2">
            
                <div class="card-header d-flex bg-info">
                    <div class="w-100 big">
                        每日
                    </div>
                    <div class="flex-shrink-0">
                        <a href="edit.php?from=daily" class="badge text-bg-danger">编辑</a>
                    </div>
                </div> 
                
                <div class="card-body">
                    $content
                </div>
            </div>
        BBB;
    }

    if (!empty($contents['weekly'])) {
        $content = $contents['weekly'];
        $content = PHPEOLToBr($content);
        $dayOfWeek = $dateDetailInfor['dayOfWeek'];
        echo <<<BBB
            <div class="card mt-2">
            
                <div class="card-header d-flex bg-info">
                    <div class="w-100 big">
                        每周
                    </div>
                    <div class="flex-shrink-0">
                        <a href="edit.php?from=weekly&dayOfWeek=$dayOfWeek" class="badge text-bg-danger">编辑</a>
                    </div>
                </div> 
                
                <div class="card-body">
                    $content
                </div>
            </div>
        BBB;
    }

    if (!empty($contents['monthly'])) {
        $content = $contents['monthly'];
        $content = PHPEOLToBr($content);
        $dayOfMonth = $dateDetailInfor['dayOfMonth'];
        echo <<<BBB
            <div class="card mt-2">
            
                <div class="card-header d-flex bg-info">
                    <div class="w-100 big">
                        每月
                    </div>
                    <div class="flex-shrink-0">
                        <a href="edit.php?from=monthly&dayOfMonth=$dayOfMonth" class="badge text-bg-danger">编辑</a>
                    </div>
                </div> 
                
                <div class="card-body">
                    $content
                </div>
            </div>
        BBB;
    }

    if (!empty($contents['yearly'])) {
        $content = $contents['yearly'];
        $content = PHPEOLToBr($content);
        $monthAndDay = $dateDetailInfor['monthAndDay'];
        echo <<<BBB
            <div class="card mt-2">
            
                <div class="card-header d-flex bg-info">
                    <div class="w-100 big">
                        每年
                    </div>
                    <div class="flex-shrink-0">
                        <a href="edit.php?from=yearly&monthAndDay=$monthAndDay" class="badge text-bg-danger">编辑</a>
                    </div>
                </div> 
                
                <div class="card-body">
                    $content
                </div>
            </div>
        BBB;
    }

    ?>

</div>

<!-- ----------------------------------------------------------------------- -->

<script src="resources/bootstrap-5.2.0-beta1-dist/js/bootstrap.min.js"></script>

<!-- ----------------------------------------------------------------------- -->

<script>
    function utf8_to_b64(str) {
        return window.btoa(unescape(encodeURIComponent(str)));
    }

    function b64_to_utf8(str) {
        return decodeURIComponent(escape(window.atob(str)));
    }
</script>

<!-- ----------------------------------------------------------------------- -->

<script>

    var finishedTasksJsonString = ""

    // 从数据库中读取指定日期内的「已完成的事务」
    function readFromFinished(date) {

        var url = "ajax/readFromFinished.php?date=" + date

        $.get({
            url: url,
            async: false
        })
            .done(function( data ) {
                finishedTasksJsonString = data
            })
            .fail(function () {
                alert("请求失败。")
            });

    }

    // 向数据库中写入指定日期内的「已完成的事务」
    function writeToFinished(content, date) {

        var url = "ajax/writeToFinished.php"

        $.post({
            url: url,
            data: {content: content, date: date},
            async: false
        })
            .done(function () {
                console.log("数据写入成功。")
            })
            .fail(function () {
                alert("请求失败。")
            })

    }

</script>

<!-- ----------------------------------------------------------------------- -->

<script>

    // 点击「待办事务描述文字」前面的「复选框」时执行

    $(".taskItem").change(function () {

        readFromFinished("<?php echo $dateStr; ?>")

        var finishedTasks = []
        if (finishedTasksJsonString !== "") {
            // arr string to arr
            finishedTasksJsonString = b64_to_utf8(finishedTasksJsonString)
            finishedTasks = JSON.parse(finishedTasksJsonString)
        }

        // 取得「待办事务描述文字」
        var taskTitle = $(this).next().text()
        taskTitle = taskTitle.trim()

        if ($(this).is(':checked')) {
            finishedTasks.push(taskTitle)
            // 数组去重
            finishedTasks = Array.from(new Set(finishedTasks))
        } else {
            var index = finishedTasks.indexOf(taskTitle)
            finishedTasks.splice(index, 1)
        }

        // arr to arr string
        finishedTasksJsonString = JSON.stringify(finishedTasks)
        finishedTasksJsonString = utf8_to_b64(finishedTasksJsonString)
        writeToFinished(finishedTasksJsonString, "<?php echo $dateStr; ?>")

    })
</script>

<!-- ----------------------------------------------------------------------- -->

<script>

    // 网页加载时执行

    readFromFinished("<?php echo $dateStr; ?>")

    if (finishedTasksJsonString !== "") {

        // arr string to arr
        finishedTasksJsonString = b64_to_utf8(finishedTasksJsonString)
        var finishedTasks = JSON.parse(finishedTasksJsonString)

        if (finishedTasks.length !== 0) {
            var arr = $(".taskItem")

            for (var item of arr) {
                var taskTitle = $(item).next().text().trim()
                for (var f in finishedTasks) {
                    if (finishedTasks[f] == taskTitle) {
                        $(item).attr("checked", true)
                    }
                }
            }
        }

    }

</script>

<!-- ----------------------------------------------------------------------- -->

<script>
    // 点击待办事务描述文字时，点击相应的复选框
    $(".taskTitle").click(function () {
        $($(this).prev()).click()
    })
</script>

<!-- ----------------------------------------------------------------------- -->

<!-- 添加「返回顶部按钮」 -->
<script src="resources/vanilla-back-to-top-master/vanilla-back-to-top.min.js"></script>
<script>
    addBackToTop({
        zIndex: 2000,
        diameter: 56,
        scrollDuration: 300,
        backgroundColor: 'rgb(255, 82, 82)',
        textColor: '#fff'
    })
</script>

<!-- ----------------------------------------------------------------------- -->

<script>

    // 快捷键
    var keyGPressed = 0;
    $(window).keydown(function(event){

        keyPressed = (String.fromCharCode(event.which).toLowerCase())

        switch (keyPressed) {
            case "i":
                // 进入编辑
                keyGPressed = 0;
                window.open("<?php echo 'edit.php?from=specificDate&date=' . $dateStr; ?>", "_self");
                break
            case "g":
                // 返回顶部
                if (keyGPressed == 1) {
                    $("html, body").animate({ scrollTop: 0});
                    keyGPressed = 0
                } else {
                    keyGPressed = 1
                }
                break
            case "j":
                keyGPressed = 0;
                // 屏幕向下滚动一小段距离
                var y = $(window).scrollTop();
                $('html, body').animate({ scrollTop: y + 650})
                break;
            case "k":
                keyGPressed = 0;
                // 屏幕向上滚动一小段距离
                var y = $(window).scrollTop();
                $('html, body').animate({ scrollTop: y - 650})
                break;
            default:
                keyGPressed = 0;
                break;
        }

        // 滚动到屏幕底部
        if (event.shiftKey) {
            switch (String.fromCharCode(event.which).toLowerCase()) {
                case 'g':
                    keyGPressed = 0;
                    $("html, body").animate({ scrollTop: $(document).height() }, 1000);
                    break
            }
        }

    })
</script>

<!-- ----------------------------------------------------------------------- -->

</body>
</html>
